<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
	<meta name="keywords" content="dynamic-route-zuul-nacos" />
	<meta name="description" content="dynamic-route-zuul-nacos" />
	<!-- 网页标签标题 -->
	<title>dynamic-route-zuul-nacos</title>
	<link rel="shortcut icon" href="/img/nacos.ico"/>
	<link rel="stylesheet" href="/build/blogDetail.css" />
</head>
<body>
	<div id="root"><div class="blog-detail-page" data-reactroot="" data-reactid="1" data-react-checksum="1895348355"><header class="header-container header-container-normal" data-reactid="2"><div class="header-body" data-reactid="3"><a href="/en-us/index.html" data-reactid="4"><img class="logo" src="/img/nacos_colorful.png" data-reactid="5"/></a><span class="language-switch language-switch-normal" data-reactid="6">中</span><div class="header-menu" data-reactid="7"><img class="header-menu-toggle" src="/img/menu_gray.png" data-reactid="8"/><ul data-reactid="9"><li class="menu-item menu-item-normal" data-reactid="10"><a href="/en-us/index.html" data-reactid="11">HOME</a></li><li class="menu-item menu-item-normal" data-reactid="12"><a href="/en-us/docs/quick-start.html" data-reactid="13">DOCS</a></li><li class="menu-item menu-item-normal menu-item-normal-active" data-reactid="14"><a href="/en-us/blog" data-reactid="15">BLOG</a></li><li class="menu-item menu-item-normal" data-reactid="16"><a href="/en-us/community" data-reactid="17">COMMUNITY</a></li><li class="menu-item menu-item-normal" data-reactid="18"><a href="http://console.nacos.io/nacos/index.html" data-reactid="19">DEMO-CONSOLE</a></li></ul></div></div></header><section class="blog-content markdown-body" data-reactid="20"><blockquote>
<p>authors:叶志远</p>
</blockquote>
<h3>一.前言</h3>
<p>Nacos是阿里巴巴开源的致力于服务发现与管理、动态配置管理，以及动态DNS服务的中间件，目前已发布至0.5.0版本，除了与Spring Cloud更加紧密结合以外，还丧心病狂地支持JDK11。如果您目前的项目碍于Eureka的性能，而又缺乏成本引进Consul，那么Nacos是您最好的选择。好了，回到正题，在上周许进搞了一个<a href="http://xujin.org/sc/gw/gw10/">使用Nacos实现Spring Cloud Gateway的动态路由</a>，让我们直观地感受到了Nacos的无缝接入如丝般顺滑，作为Spring Cloud中网关的始祖Zuul，自然也需要这一贴心赋能。</p>
<h3>二.Spring Cloud Zuul动态路由实现思路</h3>
<p>在社区书籍《重新定义Spring Cloud实战》中第8章4小节，详细剖析了Zuul的路由配置表加载以及刷新原理，其大致思想就是重写SimpleRouteLocator类的locateRoutes()方法，同时实现RefreshableRouteLocator接口，方法体引用父类的doRefresh()方法。在书中使用DB作为配置存放的仓库，如今有更为强大的Nacos，只需要将之前读取DB的逻辑换成读取Nacos即可。美中不足的是，由于Nacos还需进一步完善，目前对Spring Cloud中的事件支持还不是很完美，动态刷新只能依靠Zuul的内部逻辑。</p>
<h3>三.具体实现</h3>
<h5>1.在zuul-server中添加Nacos的配置</h5>
<pre><code>	&lt;dependency&gt;
		&lt;groupId&gt;com.alibaba.nacos&lt;/groupId&gt;
		&lt;artifactId&gt;nacos-client&lt;/artifactId&gt;
		&lt;version&gt;0.4.0&lt;/version&gt;
	&lt;/dependency&gt;
</code></pre>
<h5>2.读取Nacos配置信息核心代码</h5>
<pre><code>@Component
public class PropertiesAssemble{

	public Map&lt;String, ZuulRoute&gt; getProperties() {
		Map&lt;String, ZuulRoute&gt; routes = new LinkedHashMap&lt;&gt;();
		List&lt;ZuulRouteEntity&gt; results = listenerNacos(&quot;zuul-server&quot;,&quot;zuul_route&quot;);
		for (ZuulRouteEntity result : results) {
			if (StringUtils.isBlank(result.getPath())
					/*|| org.apache.commons.lang3.StringUtils.isBlank(result.getUrl())*/) {
				continue;
			}
			ZuulRoute zuulRoute = new ZuulRoute();
			try {
				BeanUtils.copyProperties(result, zuulRoute);
			} catch (Exception e) {
			}
			routes.put(zuulRoute.getPath(), zuulRoute);
		}
		return routes;
	}

	private List&lt;ZuulRouteEntity&gt; listenerNacos (String dataId, String group) {
		try {
			Properties properties = new Properties();
			properties.put(PropertyKeyConst.SERVER_ADDR, &quot;localhost:8848&quot;);
			ConfigService configService = NacosFactory.createConfigService(properties);
			String content = configService.getConfig(dataId, group, 5000);
			System.out.println(&quot;从Nacos返回的配置：&quot; + content);
			//注册Nacos配置更新监听器，用于监听触发
//            configService.addListener(dataId, group, new Listener()  {
//                @Override
//                public void receiveConfigInfo(String configInfo) {
//                    System.out.println(&quot;Nacos更新了！&quot;);
//
//                }
//                @Override
//                public Executor getExecutor() {
//                    return null;
//                }
//            });
			return JSONObject.parseArray(content, ZuulRouteEntity.class);
		} catch (NacosException e) {
			e.printStackTrace();
		}
		return new ArrayList&lt;&gt;();
	}
}
</code></pre>
<p>目前的demo写得比较简单，直接将Nacos的默认地址与端口写了进来，Nacos对于配置的管理有两个坐标，一是dataId，二是group，本demo中笔者将其分别命名为&quot;zuul-server&quot;,&quot;zuul_route&quot;。</p>
<h5>3.Zuul动态刷新路由实现</h5>
<p>这部分可以查看demo地址：<a href="https://github.com/SpringCloud/spring-cloud-zuul-nacos">https://github.com/SpringCloud/spring-cloud-zuul-nacos</a>，具体就不赘述。</p>
<h3>四.演示</h3>
<h5>1.从Nacos github地址pull源码，配置环境</h5>
<p><img src="https://img-blog.csdnimg.cn/20181129002717633.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JpY2tpeWVhdA==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述">
这里需要在IDEA中添加启动参数-Dnacos.standalone=true
<img src="https://img-blog.csdnimg.cn/20181129002856286.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JpY2tpeWVhdA==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<h5>2.启动Nacos，配置Zuul路由信息</h5>
<p>启动Nacos后，在浏览器输入<a href="http://localhost:8848/nacos/index.html">http://localhost:8848/nacos/index.html</a>便会跳转到如下页面：
<img src="https://img-blog.csdnimg.cn/2018112900323177.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JpY2tpeWVhdA==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述">
点击配置列表，单击右侧的+号图标，便可以新增一项配置，由于这里已经添加好了，就直接看信息：
<img src="https://img-blog.csdnimg.cn/20181129003545464.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JpY2tpeWVhdA==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<h5>3.启动zuul-server，从Nacos加载路由信息测试</h5>
<p>启动Zuul后，console中出现如下信息：
<img src="https://img-blog.csdnimg.cn/20181129003851880.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JpY2tpeWVhdA==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述">
在浏览器输入<a href="http://localhost:5555/baidu">http://localhost:5555/baidu</a>,出现如下效果，直接跳转到目标地址：
<img src="https://img-blog.csdnimg.cn/2018112900414387.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JpY2tpeWVhdA==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述">
我们现在将Nacos中的配置修改一下，将http://github.com/Lovnx换成http://www.baidu.com，修改后直接发布：
<img src="https://img-blog.csdnimg.cn/20181129004408166.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JpY2tpeWVhdA==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述">
我们会在console看到：
<img src="https://img-blog.csdnimg.cn/20181129004524375.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JpY2tpeWVhdA==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述">
在浏览器输入<a href="http://localhost:5555/baidu">http://localhost:5555/baidu</a>,出现如下效果：
<img src="https://img-blog.csdnimg.cn/20181129004810756.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JpY2tpeWVhdA==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<h2><a href="https://github.com/SpringCloud/spring-cloud-zuul-nacos">-------------------&gt;&gt;&gt;DEMO源码</a></h2>
</section><footer class="footer-container" data-reactid="21"><div class="footer-body" data-reactid="22"><img src="/img/nacos_gray.png" data-reactid="23"/><div class="cols-container" data-reactid="24"><div class="col col-12" data-reactid="25"><h3 data-reactid="26">Vision</h3><p data-reactid="27">By providing an easy-to-use service infrastructure such as dynamic service discovery, service configuration, service sharing and management and etc., Nacos help users better construct, deliver and manage their own service platform, reuse and composite business service faster and deliver value of business innovation more quickly so as to win market for users in the era of cloud native and in all cloud environments, such as private, mixed, or public clouds.</p></div><div class="col col-6" data-reactid="28"><dl data-reactid="29"><dt data-reactid="30">Documentation</dt><dd data-reactid="31"><a href="/en-us/docs/what-is-nacos.html" target="_self" data-reactid="32">Overview</a></dd><dd data-reactid="33"><a href="/en-us/docs/quick-start.html" target="_self" data-reactid="34">Quick start</a></dd><dd data-reactid="35"><a href="/en-us/docs/contributing.html" target="_self" data-reactid="36">Developer guide</a></dd></dl></div><div class="col col-6" data-reactid="37"><dl data-reactid="38"><dt data-reactid="39">Resources</dt><dd data-reactid="40"><a href="/en-us/community/index.html" target="_self" data-reactid="41">Community</a></dd></dl></div></div><div class="copyright" data-reactid="42"><span data-reactid="43">@ 2018 The Nacos Authors | An Alibaba Middleware (Aliware) Project</span></div></div></footer></div></div>
	<script src="https://f.alicdn.com/react/15.4.1/react-with-addons.min.js"></script>
	<script src="https://f.alicdn.com/react/15.4.1/react-dom.min.js"></script>
	<script>
		window.rootPath = '';
  </script>
	<script src="/build/blogDetail.js"></script>
</body>
</html>